<?php

namespace App\Http\Controllers;
use App\Common\Constant;
use App\Common\ResponseCode;
use App\Repository\MerchantsInfoRepo;
use App\Repository\OpenPlatformRepo;
use App\Service\Common\CheckSignService;
use App\Traits\VerifyRequestParam;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Laravel\Lumen\Routing\Controller;
/**
 * 基础控制器
 *
 * @package App\Http\Controllers
 * @author WangBin
 * @date 2021-08-12
 */
class BaseController extends Controller
{
    use VerifyRequestParam;

    /**
     * 统一返回结果处理
     *
     * @param $responseCode
     * @param null $data
     * @param array $extend
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\BusinessException
     */
    private function codeReturn($responseCode, $data = null, array $extend = [])
    {
        list($errno, $errmsg) = $responseCode;
        $ret = ['error_code' => $errno, 'error_msg' => $errmsg];

        // 附加的信息
        if(!empty($extend)) {
            $field = array_keys($extend)[0];
            $ret['error_msg'] = str_replace( '%' . $field, ',' . $extend[$field], $ret['error_msg']);
        } else {
            $ret['error_msg'] = preg_replace("/%[a-z]+/", '', $errmsg);
        }

        if (env('APP_ENV') == 'local')
        {
            $ret['data'] = !is_null($data) ? $data : '';
            return response()->json($ret);
        }
        $result = '';
        if (!is_null($data))
            $result = $data;
        $error_msg = trim($ret['error_msg'],",");
        $err = ['error_code'=>2,"error_msg" => "",'data'=>'','sign'=>'','encryptKey'=>'','timestamp'=>time()];
        $access_mode = request('access_mode');
        // 接入模式参数校验 platform 平台接入  creator创作者接入
        if (!in_array($access_mode,['platform','creator']))
        {
            $err['error_msg'] = '接入模式参数错误';
            return response()->json($err);
        }

        // 获取商户公钥
        $access_mid = request('access_mid');
        $cacheInfo = Cache::get(Constant::MERCHANTID.':'.$access_mid);

        if (empty($cacheInfo))
        {
            if ($access_mode == 'platform')
            {
                $merchantsInfo = OpenPlatformRepo::getInstance()->getByPlatformNo($access_mid);
                if (empty($merchantsInfo))
                {
                    $err['error_msg'] = '平台商户不存在';
                    return response()->json($err);
                }

                if (empty($merchantsInfo->public_key))
                {
                    $err['error_msg'] = '平台商户未配置必要信息';
                    return response()->json($err);
                }
            }
            if ($access_mode == 'creator')
            {
                // 获取创作者商户信息
                $merchantsInfo = MerchantsInfoRepo::getInstance()->getByMerchantIdRepo($access_mid);
                if (empty($merchantsInfo))
                {
                    $err['error_msg'] = '创作者商户不存在';
                    return response()->json($err);
                }


                if (empty($merchantsInfo->public_key))
                {
                    $err['error_msg'] = '创作者商户未配置必要信息';
                    return response()->json($err);
                }
            }

            // 反向写入cache
            Cache::put(Constant::MERCHANTID.':'.$access_mid,json_encode($merchantsInfo));
            $cacheInfo = Cache::get(Constant::MERCHANTID.':'.$access_mid);
        }
        $cacheMerchants = json_decode($cacheInfo,true);
        $publicKey = $cacheMerchants['public_key'];

        // 获取平台自身私钥
        $privateKeyPath = config('selfpem.self_private');
        $privateKey = file_get_contents($privateKeyPath);


        // 加密加签名
        $encrypt['error_code']=$errno;
        $encrypt['error_msg']=$error_msg;
        $encrypt['data']=$result;
        $ret = CheckSignService::getInstance()->selfRequestCreateSign($encrypt,$publicKey,$privateKey);
        $ret['error_code']=$errno;
        $ret['error_msg']=$error_msg;
        return response()->json($ret);
    }

    /**
     * 返回成功结果
     *
     * @param null $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($data = null)
    {
        return $this->codeReturn(ResponseCode::SUCCESS, $data);
    }

    /**
     * 返回失败结果
     *
     * @param array $responseCode
     * @param array $extend
     * @return \Illuminate\Http\JsonResponse
     */
    protected function fail(array $responseCode, array $extend = [])
    {
        return $this->codeReturn($responseCode, null, $extend);
    }

    /**
     * @param array $responseCode
     * @param array $extend
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\BusinessException
     */
    protected function abc(array $responseCode, array $extend = [])
    {
        return $this->codeReturn($responseCode, null, $extend);
    }
}
